package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

import dto.DataManager;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username, password;

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		DataManager dataManager = new DataManager();

		username = request.getParameter("username");
		password = request.getParameter("password");
		String categoryId = request.getParameter("categoryId");
		if (dataManager.isUser(username, password)) {
			User user = dataManager.getUserWithUserName(username);
			session.setAttribute("username", username);
			session.setAttribute("roleId", user.getRoleId());
			session.setAttribute("userId", user.getUserId());
			
			response.sendRedirect("default.jsp"
					+ (categoryId.equals("-1") ? "" : "?categoryId="
							+ categoryId));
		} else {
			response.sendRedirect("default.jsp?err=true");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
